package cn.rui.service.impl;

import cn.rui.constant.MessageConstant;
import cn.rui.entity.QueryPageBean;
import cn.rui.entity.Result;
import cn.rui.mapper.*;
import cn.rui.pojo.Member;
import cn.rui.pojo.Order;
import cn.rui.pojo.OrderSetting;
import cn.rui.pojo.Setmeal;
import cn.rui.service.OrderService;
import cn.rui.utils.DateUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 徽州大都督
 * @date 2020/8/28
 */
@Service
@Transactional
@org.springframework.stereotype.Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private MemberMapper memberMapper;


    @Override
    public Result order(Map map) throws Exception {


        //检查用户所选择的日期是否已经提前进行了预约设置，如果没有则无法进行预约
        String dateStr = (String) map.get ("orderDate");
        Date date = DateUtils.parseString2Date (dateStr);
        OrderSetting orderSetting = orderSettingMapper.findOrderSettingByDate (date);
        if (orderSetting == null) {
            return new Result (false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //检查用户所选择的日期是否已经约满，如果满了就不能预约
        if (orderSetting.getReservations () >= orderSetting.getNumber ()) {
            //已经满了
            return new Result (false, MessageConstant.ORDER_FULL);
        }else {

            //检查用户是否重复预约（同一个用户在同一天预约了同一个套餐）
            String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
            Member member = reportMapper.findByTelephone(telephone);

            if(member != null){
                //判断是否在重复预约
                Integer memberId = member.getId();//会员ID
                String setmealId = (String) map.get("setmealId");//套餐ID
                Order order = new Order(memberId, date, Integer.parseInt(setmealId));
                //根据条件进行查询
                List<Order> list = orderMapper.findByCondition(order);
                if(list != null && list.size() > 0){
                    //说明用户在重复预约，无法完成再次预约
                    return new Result(false,MessageConstant.HAS_ORDERED);
                }
            }else {
                //检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
                member = new Member();
                member.setName((String) map.get("name"));
                member.setPhoneNumber(telephone);
                member.setIdCard((String) map.get("idCard"));
                member.setSex((String) map.get("sex"));
                member.setRegTime(new Date());
                reportMapper.add(member);//自动完成会员注册
            }

            //5、预约成功，更新当日的已预约人数
            Order order = new Order();
            order.setMemberId(member.getId());//设置会员ID
            order.setOrderDate(date);//预约日期
            order.setOrderType((String) map.get("orderType"));//预约类型
            order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
            order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
            orderMapper.add(order);

            orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
            orderSettingMapper.editReservationsByOrderDate(orderSetting);

            return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
        }


    }

    /**
     * 预约成功后信息回显
     * <p>体检人：{{orderInfo.member}}</p>
     * <p>体检套餐：{{orderInfo.setmeal}}</p>
     * <p>体检日期：{{orderInfo.orderDate}}</p>
     * <p>预约类型：{{orderInfo.orderType}}</p>
     */
    public Map<String, Object> findById(Integer id) {

        Map<String, Object> detail = orderMapper.findById4Detail (id);

        return detail;
    }

    /**
     * 分页查询预约信息
     * @param queryPageBean
     * @return
     */
    @Override
    public List<Map<String, Object>> findPage(QueryPageBean queryPageBean) throws Exception {

        Integer pageSize = queryPageBean.getPageSize ();
        Integer currentPage = queryPageBean.getCurrentPage ();
        String queryString = queryPageBean.getQueryString ();
        PageHelper.startPage (currentPage,pageSize);

        Page<Order> page =orderMapper.selectByCondition(queryString);
        List<Order> orderList = page.getResult ();
        long total = page.getTotal ();


        List<Map<String, Object>> mapList=new ArrayList<> ();

        for (Order order : orderList) {
            Map<String,Object> map = new HashMap<> ();

            //根据id查询套餐信息
            Setmeal setmeal = setmealMapper.findById (order.getSetmealId ());


            map.put ("setmealName",setmeal.getName ());
            //根据id查询预约人的信息
            Member member=memberMapper.findById(order.getMemberId ());
            map.put ("name",member.getName ());
            map.put ("orderType",order.getOrderType ());
            map.put ("id",order.getId ());
            map.put ("orderDate",DateUtils.parseDate2String (order.getOrderDate ()));
            map.put ("orderStatus",order.getOrderStatus ());
            map.put ("telephone",member.getPhoneNumber ());
            map.put ("total",total);
            mapList.add (map);
        }



        return mapList;
    }

    /**
     * 根据id删除预约信息
     * @param id
     */
    @Override
    public void deleteById(Integer id) throws Exception{

        Order order=orderMapper.findById(id);

        //删除预约信息
        orderMapper.deleteById(id);

        //当天的已预约数-1
        OrderSetting orderSetting = orderSettingMapper.findByOrder (DateUtils.parseDate2String (order.getOrderDate ()));
        orderSetting.setReservations (orderSetting.getReservations ()-1);
        orderSettingMapper.editReservationsByOrderDate(orderSetting);
    }

    /**
     * 更改到诊状态
     */
    public void orderUpdateType(Integer id) {
        Order order = orderMapper.findById (id);
        if (order.getOrderStatus ().equals ("未到诊")){
            order.setOrderStatus ("已到诊");
        }else {
            order.setOrderStatus ("未到诊");
        }

        orderMapper.orderUpdateType(order);

    }
}
